use std::str::FromStr;

#[derive(Debug, PartialEq)]
struct Number {
    number_str: String, // 文本形式存储数值
    radix: u32,         // 表示数值为几进制
}

#[derive(Debug, PartialEq, Eq)]
struct ParseNumberError;

impl FromStr for Number {
    type Err = ParseNumberError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (number_str, radix) = s
            .strip_suffix(')')
            .and_then(|s| s.split_once('('))
            .ok_or(ParseNumberError)?;

        let number_str = number_str.to_string();
        let radix = radix.parse().map_err(|_| ParseNumberError)?;

        Ok(Self { number_str, radix })
    }
}

/// ⽀持任意2-16进制数之间转换，如：2进制转7进制，7进制转16进制，15进制转8进制等。(20)
pub fn convert_base(num_str: &str, base: u32) -> String {
    let number: Number = num_str.parse().expect("Invalid number string");
    let mut num = u128::from_str_radix(&number.number_str, number.radix).unwrap();
    let mut result = String::new();
    let base: u128 = base.into();
    while num > 0 {
        result.push_str(&format!("{:x}", num % base));
        num /= base;
    }
    result.chars().rev().collect()
}
